<template>
  <view class="login-container">
    <!-- 标题区域 -->
    <view class="title-area">
      <text class="main-title">智慧农业助手</text>
      <text class="sub-title">走进智慧农业，创建幸福生活</text>
    </view>
    
    <!-- 登录表单 -->
    <view class="login-form-box">
      <view class="login-type">
        <text :class="{'active-type': loginType === 'account', 'inactive-type': loginType !== 'account'}" @click="switchLoginType('account')">账号密码登录</text>
        <text :class="{'active-type': loginType === 'phone', 'inactive-type': loginType !== 'phone'}" @click="switchLoginType('phone')">手机号验证登录</text>
      </view>
      
      <!-- 账号密码登录表单 -->
      <uni-forms v-if="loginType === 'account'" ref="accountFormRef" :modelValue="accountForm" :rules="accountRules" validateTrigger="submit">
        <uni-forms-item name="username">
          <uni-easyinput
            v-model="accountForm.username"
            placeholder="请输入用户名/手机号"
            prefixIcon="person"
            :styles="inputStyles"
          />
        </uni-forms-item>
        
        <uni-forms-item name="password">
          <uni-easyinput
            v-model="accountForm.password"
            type="password"
            placeholder="请输入密码"
            prefixIcon="locked"
            :styles="inputStyles"
          />
        </uni-forms-item>
        
        <button class="login-btn" @click="handleAccountLogin">登 录</button>
      </uni-forms>
      
      <!-- 手机号验证登录表单 -->
      <uni-forms v-else ref="phoneFormRef" :modelValue="phoneForm" :rules="phoneRules" validateTrigger="submit">
        <uni-forms-item name="phone">
          <uni-easyinput
            v-model="phoneForm.phone"
            placeholder="请输入手机号"
            prefixIcon="phone"
            :styles="inputStyles"
          />
        </uni-forms-item>
        
        <uni-forms-item name="verifyCode">
          <view class="verify-code-container">
            <uni-easyinput
              v-model="phoneForm.verifyCode"
              placeholder="请输入验证码"
              prefixIcon="locked"
              :styles="inputStyles"
            />
            <button class="verify-code-btn" :disabled="isCounting" @click="getVerifyCode">
              {{ isCounting ? `${countdown}s后重新获取` : '获取验证码' }}
            </button>
          </view>
        </uni-forms-item>
        
        <button class="login-btn" @click="handlePhoneLogin">登 录</button>
      </uni-forms>
    </view>
    
    <!-- 第三方登录 -->
   <!-- 第三方登录 -->
   <view class="third-party-login">
     <text class="third-party-title">使用第三方账号登录</text>
     <view class="third-party-icons">
       <view class="icon-item">
         <uni-icons type="qq" size="30" color="#12B7F5"></uni-icons>
       </view>
       <view class="icon-item">
         <uni-icons type="weixin" size="30" color="#07C160"></uni-icons>
       </view>
       <view class="icon-item">
         <uni-icons type="weibo" size="30" color="#E6162D"></uni-icons>
       </view>
     </view>
     <view class="register-tip">
       <text>没有账号？</text>
       <text class="register-link" @click="goToRegister">立即注册</text>
     </view>
   </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
// 引入 uni 对象
// import uni from '@dcloudio/uni-app';

// 登录类型（账号密码登录/手机号验证登录）
const loginType = ref('account');

// 账号密码登录表单数据
const accountForm = reactive({
  username: '',
  password: ''
});

// 手机号验证登录表单数据
const phoneForm = reactive({
  phone: '',
  verifyCode: ''
});

// 表单引用
const accountFormRef = ref(null);
const phoneFormRef = ref(null);

// 验证码倒计时
const isCounting = ref(false);
const countdown = ref(60);

// 输入框样式
const inputStyles = {
  borderRadius: '5px',
  border: '1px solid #e5e5e5'
};

// 自定义校验规则 - 手机号
const validatePhone = (rule, value, data, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(value)) {
    callback('请输入正确的手机号码');
    return false;
  }
  return true;
};

// 账号密码登录表单校验规则
const accountRules = {
  // 用户名校验
  username: {
    rules: [
      { required: true, errorMessage: '请输入用户名/手机号' },
      { minLength: 3, errorMessage: '用户名长度不能少于3个字符' }
    ]
  },
  // 密码校验
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { minLength: 6, errorMessage: '密码长度不能少于6位' }
    ]
  }
};

// 手机号验证登录表单校验规则
const phoneRules = {
  // 手机号校验
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { validateFunction: validatePhone }
    ]
  },
  // 验证码校验
  verifyCode: {
    rules: [
      { required: true, errorMessage: '请输入验证码' },
      { pattern: /^\d{6}$/, errorMessage: '验证码为6位数字' }
    ]
  }
};

// 切换登录类型
const switchLoginType = (type) => {
  loginType.value = type;
};

// 获取验证码
const getVerifyCode = () => {
  // 先校验手机号
  phoneFormRef.value.validateField(['phone']).then(res => {
    // 手机号校验通过，发送验证码
    startCountdown();
    
    // 模拟发送验证码请求
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    });
  }).catch(err => {
    console.log('手机号校验失败:', err);
  });
};

// 开始倒计时
const startCountdown = () => {
  isCounting.value = true;
  countdown.value = 60;
  
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
    }
  }, 1000);
};

// 账号密码登录
const handleAccountLogin = () => {
  if (!accountFormRef.value) {
    console.error('accountFormRef 未正确初始化');
    return;
  }
  if (!accountForm) {
    console.error('accountForm 未定义');
    return;
  }
  accountFormRef.value.validate().then(res => {
    // 表单校验通过，执行登录逻辑
    uni.request({
      url: 'http://192.168.136.5:4523/m1/6241752-5935568-default/login',
      data: accountForm,
      method: 'POST',
      success: (res) => {
        console.log("【响应结果】" + JSON.stringify(res.data));
        // 登录成功后跳转到首页
        // uni.switchTab({
        //   url: '/pages/index/index'
        // });
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
      }
    });
  }).catch(err => {
    console.log('表单校验失败，详细信息:', JSON.stringify(err));
  });
};
// 手机号验证登录
const handlePhoneLogin = () => {
  phoneFormRef.value.validate().then(res => {
    // 表单校验通过，执行登录逻辑
    console.log('手机号验证登录信息:', phoneForm);
    
    // 模拟登录请求
    uni.showLoading({
      title: '登录中...'
    });
    
    setTimeout(() => {
      uni.hideLoading();
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 登录成功后跳转到首页
      // uni.switchTab({
      //   url: '/pages/index/index'
      // });
    }, 1500);
  }).catch(err => {
    console.log('表单校验失败:', err);
  });
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/register/index'
  });
};
</script>

<style>
.login-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #a8e6cf 0%, #d6f3ff 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}

.title-area {
  margin-top: 80rpx;
  text-align: center;
}

.main-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #2a9d8f;
}

.sub-title {
  font-size: 28rpx;
  color: #2a9d8f;
  margin-top: 20rpx;
  display: block;
}

.login-form-box {
  width: 100%;
  max-width: 650rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin-top: 60rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.login-type {
  display: flex;
  border-bottom: 1px solid #eee;
  padding-bottom: 20rpx;
  margin-bottom: 30rpx;
}

.active-type {
  color: #2a9d8f;
  font-size: 28rpx;
  position: relative;
  margin-right: 40rpx;
  font-weight: bold;
}

.active-type::after {
  content: '';
  position: absolute;
  bottom: -20rpx;
  left: 0;
  width: 100%;
  height: 4rpx;
  background-color: #2a9d8f;
}

.inactive-type {
  color: #999;
  font-size: 28rpx;
  margin-right: 40rpx;
}

/* 隐藏uni-forms-item的label */
:deep(.uni-forms-item__label) {
  display: none;
}

/* 调整uni-forms-item的间距 */
:deep(.uni-forms-item__content) {
  display: flex;
}

/* 调整错误提示的样式 */
:deep(.uni-error-message) {
  padding-left: 4px;
  color: #f56c6c;
  font-size: 24rpx;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #4db6ac;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
  border: none;
}

.verify-code-container {
  display: flex;
  width: 100%;
}

.verify-code-btn {
  width: 220rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 24rpx;
  background-color: #4db6ac;
  color: #fff;
  border: none;
  border-radius: 35rpx;
  margin-left: 20rpx;
  padding: 0;
  white-space: nowrap;
}

.verify-code-btn[disabled] {
  background-color: #ccc;
}

.third-party-login {
  margin-top: 80rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-party-title {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.third-party-icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
}

.icon-item {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.third-icon {
  width: 50rpx;
  height: 50rpx;
}

.register-tip {
  margin-top: 40rpx;
  font-size: 26rpx;
  color: #666;
}

.register-link {
  color: #4db6ac;
  margin-left: 10rpx;
}
</style>